﻿using System;
using System.Net.Mail;
using System.Threading;
using Common.Dao;

namespace TdxApiPool.ErrorHandler
{
    public class EmailSenter
    {
        private static readonly log4net.ILog _log = log4net.LogManager.GetLogger(typeof(EmailSenter));
      
        public static void SendEmail(string title ,string message)
        {
            System.Threading.Tasks.Task.Factory.StartNew(new Action(() => SendEmailSync(title,message)));
        }

        private static bool SendEmailSync(string title, string message)
        {
            if (!IsTradeTime())
            {
                return true;

            }
            string host = "smtp.163.com";// 邮件服务器smtp.163.com表示网易邮箱服务器    
            string userName = "guosen_fs@163.com";// 发送端账号
            string password = "fs95536";// 发送端密码(这个客户端重置后的密码)

            SmtpClient client = new SmtpClient
            {
                DeliveryMethod = SmtpDeliveryMethod.Network,
                Host = host,
                UseDefaultCredentials = true,
                Credentials = new System.Net.NetworkCredential(userName, password)
            };
            
            //指定电子邮件发送方式    
            //邮件服务器
            //用户名、密码

            //////////////////////////////////////
            string strfrom = userName;
            string strto = "443201683@qq.com";
//            string strcc = "2605625733@qq.com";//抄送


            string subject = title +"-------"+ DateTime.Now; //邮件的主题             

            string body = message + "\n\t" + DateTime.Now;//发送的邮件正文  

            System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage
            {
                From = new MailAddress(strfrom, "行情服务邮件")
            };
            
            msg.To.Add(strto);
//            msg.CC.Add(strcc);

            msg.Subject = subject;//邮件标题   
            msg.Body = body;//邮件内容   
            msg.BodyEncoding = System.Text.Encoding.UTF8;//邮件内容编码   
            msg.IsBodyHtml = true;//是否是HTML邮件   
            msg.Priority = MailPriority.High;//邮件优先级   

            try
            {
                client.Send(msg);
                _log.Info("email send success");
                return true;
            }
            catch (System.Net.Mail.SmtpException ex)
            {
                _log.Info(ex.Message+" email send success");
                return false;
            }     
        }
            
        
        private static bool IsTradeTime()
        {
            if (!TradeDateDao.IsTradeDate(DateTime.Today))
            {
                return false;
            }
            var begin = DateTime.Today.AddHours(9);
            var end = DateTime.Today.AddHours(15);
            if (DateTime.Now < begin || DateTime.Now > end)
            {
                return false;
            }
            return true;
        }
    }
}